package com.ark.frigate.dingtalk.ding;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.ark.frigate.dingtalk.ding.message.AbstractMessage;
import com.ark.frigate.dingtalk.properties.DingTalkConfig;
import com.ark.frigate.dingtalk.utils.DingTalkUtil;
import com.ark.frigate.dingtalk.utils.HttpEntityUtil;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 异常报警
 * <p>
 * https://developers.dingtalk.com/document/app/custom-robot-access
 *
 * @author zengweilong
 */
@Slf4j
@Data
public class DingTalkMessage {

    @Autowired
    protected DingTalkConfig dingTalkConfig;

    @Autowired
    protected Environment environment;

    @Autowired
    private RestTemplate restTemplate;

    public void sendCoreMessage(AbstractMessage message) throws Exception {

        if (!dingTalkConfig.getEnable()) {
            log.info("Ding message send Enable is:{}", dingTalkConfig.getEnable());
            return;
        }

        String jsonBody = message.toJson();
        // 默认URL推送
        if (StringUtils.isBlank(message.getDingTalkUrl())) {
            message.setDingTalkUrl(dingTalkConfig.getUrl());
        }
        // 默认
        if (StringUtils.isBlank(message.getSecret())) {
            message.setSecret(dingTalkConfig.getSecret());
        }
        String dingUrl = message.getDingTalkUrl();
        if (StringUtils.isBlank(dingUrl)) {
            log.warn("Pleads check the properties [ ding.talk.url ] in file [ application.yml ]");
            return;
        }
        Long timestamp = System.currentTimeMillis();
        String sign = DingTalkUtil.algorithm(timestamp, message.getSecret());
        dingUrl += "&timestamp=%s&sign=%s";
        dingUrl = String.format(dingUrl, timestamp, sign);

        log.info("Send ding talk message...body={}", jsonBody);
        HttpEntity<String> request = HttpEntityUtil.getRequest(jsonBody);
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(dingUrl, request, String.class);
        log.info("Send ding talk message end = {}", postForEntity.getBody());
    }

    protected String getEnv() {
        String[] env = environment.getActiveProfiles();
        if (env != null && env.length > 0) {
            return env[0];
        }
        env = environment.getDefaultProfiles();
        if (env != null && env.length > 0) {
            return env[0];
        }
        return StringUtils.EMPTY;
    }

}
